const jsonfile = require('jsonfile');
const {isEmpty,isObject,isNumber,isString,pick} =require('loadsh')
const fs=require('fs')
module.exports = {
    '/set':(req, res)=>{
        const {name,sign,type,step}=req.body
        if(!name || !sign || !isNumber(type)) return res.send({code:1,msg:'平台、标识和类型不能为空'});
        //type 0 code,1名称
        if(isNumber(step)){
            const platformTags=jsonfile.readFileSync(`data/tag.json`)
            platformTags[`shop_${name}`]={sign,type,step}
            jsonfile.writeFileSync(`data/tag.json`, platformTags)
            return res.send({
                code:0,
                msg:'操作成功'
            });
        }
        const platformTags=jsonfile.readFileSync(`data/tag.json`)
        if(platformTags[`shop_${name}`]){
            return res.send({code:1,msg:'平台已存在'});
        }
        jsonfile.writeFileSync(`data/shop/${sign}.json`,{type})
        platformTags[`shop_${name}`]={sign,type}
        jsonfile.writeFileSync(`data/tag.json`, platformTags)
        res.send({
            code:0,
            msg:'操作成功'
        });
    },
    '/del':(req, res)=>{
        const {platform,name}=req.body
        if(!platform || !name) return res.send({code:1,msg:'平台不能为空'});
        const platformTags=jsonfile.readFileSync(`data/tag.json`)
        const tag=Object.values(platformTags).find(i=>isString(i) && i===platform)
        if(platformTags[`shop_${name}`]){
            const listObject=jsonfile.readFileSync(`data/shop/${platform}.json`)
            if(!isEmpty(pick(listObject,Object.keys(listObject).filter(k=>!['type','isReady'].includes(k)))) || tag){
                //存在禁止删除
                return res.send({
                    code: 1,
                    msg: '平台下有数据，禁止删除',
                })
            }
            delete platformTags[`shop_${name}`]
            jsonfile.writeFileSync(`data/tag.json`,platformTags)
            fs.unlinkSync(`data/shop/${platform}.json`);
            res.send({
                code: 0,
                msg: '删除成功',
            })
        }else {
            res.send({
                code: 1,
                msg: '平台不存在',
            })
        }
    },
}
